import { Card, Modal, Space, Tag, Typography } from "antd";
import { ClockCircleOutlined, CodeOutlined, FileTextOutlined, KeyOutlined } from "@ant-design/icons";

const { Title, Text } = Typography;

/**
 * 消息详情模态框组件
 * 优化点：加深JSON字段颜色，提升对比度和可读性
 */
const MqDetail = (props) => {
    const { visible, setVisible, messageDetail = {} } = props;

    // 判断内容是否为JSON
    const isJsonContent = (content) => {
        if (typeof content !== 'string') return false;
        try {
            JSON.parse(content);
            return true;
        } catch (e) {
            return false;
        }
    };

    // 递归生成带颜色的JSON HTML结构（加深颜色版本）
    const renderJson = (data, indent = 2) => {
        if (data === null) {
            // null值：深灰色，提升对比度
            return `<span style="color: #666666; font-weight: 500;">null</span>`;
        }

        if (typeof data === 'boolean') {
            // 布尔值：深紫色，更醒目
            return `<span style="color: #800080; font-weight: 600;">${data}</span>`;
        }

        if (typeof data === 'number') {
            // 数字：深橙色/棕色，避免刺眼且清晰
            return `<span style="color: #cc5500; font-weight: 500;">${data}</span>`;
        }

        if (typeof data === 'string') {
            // 字符串：深绿色，更易识别
            return `<span style="color: #008000; font-weight: 500;">"${escapeHtml(data)}"</span>`;
        }

        // 处理数组
        if (Array.isArray(data)) {
            if (data.length === 0) return '[]';

            const items = data.map(item => {
                return `${' '.repeat(indent + 2)}${renderJson(item, indent + 2)}`;
            }).join(',\n');

            return `[\n${items}\n${' '.repeat(indent)}]`;
        }

        // 处理对象（键名用深蓝色，突出显示）
        const keys = Object.keys(data);
        if (keys.length === 0) return '{}';

        const items = keys.map(key => {
            return `${' '.repeat(indent + 2)}<span style="color: #0066cc; font-weight: 600;">"${escapeHtml(key)}"</span>: ${renderJson(data[key], indent + 2)}`;
        }).join(',\n');

        return `{\n${items}\n${' '.repeat(indent)}}`;
    };

    // HTML转义处理（防止XSS）
    const escapeHtml = (str) => {
        if (!str) return '';
        return str
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#039;');
    };

    // 格式化JSON并添加颜色样式
    const formatJsonWithColor = (content) => {
        try {
            const parsed = JSON.parse(content);
            return renderJson(parsed);
        } catch (e) {
            return escapeHtml(content);
        }
    };

    // 状态标签样式处理
    const renderStatusTag = (statusDesc) => {
        const statusMap = {
            '成功': 'green',
            '失败': 'red',
            '中': 'blue',
            '未': 'orange'
        };
        const statusColor = Object.keys(statusMap).find(key => statusDesc?.includes(key))
            ? statusMap[Object.keys(statusMap).find(key => statusDesc.includes(key))]
            : 'default';

        return (
            <Tag color={statusColor} style={{
                fontSize: '13px',
                padding: '3px 10px',
                borderRadius: '4px',
                fontWeight: 500
            }}>
                {statusDesc || '未知状态'}
            </Tag>
        );
    };

    return (
        <Modal
            open={visible}
            onCancel={() => setVisible(false)}
            title={
                <Title level={5} style={{
                    margin: 0,
                    color: '#1890ff',
                    display: 'flex',
                    alignItems: 'center',
                    gap: 8
                }}>
                    <FileTextOutlined />
                    消息详情
                </Title>
            }
            width={900}
            maskClosable={false}
            destroyOnClose={true}
            footer={null}
            style={{ top: 20 }}
            bodyStyle={{
                padding: 0,
                overflow: 'hidden'
            }}
        >
            <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
                {/* 基本信息卡片 */}
                <Card
                    bordered={false}
                    style={{
                        margin: 0,
                        boxShadow: '0 1px 2px rgba(0,0,0,0.05)',
                        borderBottom: '1px solid #f0f0f0'
                    }}
                    bodyStyle={{ padding: '20px 24px' }}
                >
                    <div style={{
                        display: 'grid',
                        gridTemplateColumns: '1fr 1fr',
                        gap: '16px 24px'
                    }}>
                        {/* 消息ID */}
                        <div style={{ display: 'flex', flexDirection: 'column' }}>
                            <Text style={{
                                color: '#6b7280',
                                fontSize: '13px',
                                marginBottom: 6,
                                display: 'flex',
                                alignItems: 'center',
                                gap: 6
                            }}>
                                <KeyOutlined style={{ fontSize: '14px' }} />
                                消息ID
                            </Text>
                            <Text
                                style={{
                                    color: '#1f2329',
                                    fontSize: '14px',
                                    wordBreak: 'break-all',
                                    fontWeight: 500
                                }}
                            >
                                {messageDetail.messageId || '无ID信息'}
                            </Text>
                        </div>

                        {/* 状态描述 */}
                        <div style={{ display: 'flex', flexDirection: 'column' }}>
                            <Text style={{
                                color: '#6b7280',
                                fontSize: '13px',
                                marginBottom: 6
                            }}>
                                状态
                            </Text>
                            <div>{renderStatusTag(messageDetail.statusDesc)}</div>
                        </div>

                        {/* 生产时间 */}
                        <div style={{ display: 'flex', flexDirection: 'column', gridColumn: '1 / 3' }}>
                            <Text style={{
                                color: '#6b7280',
                                fontSize: '13px',
                                marginBottom: 6,
                                display: 'flex',
                                alignItems: 'center',
                                gap: 6
                            }}>
                                <ClockCircleOutlined style={{ fontSize: '14px' }} />
                                生产时间
                            </Text>
                            <Text style={{
                                color: '#096b72',
                                fontSize: '14px',
                                fontWeight: 500
                            }}>
                                {messageDetail.sendTime || '未知时间'}
                            </Text>
                        </div>
                    </div>
                </Card>

                {/* 消息内容区域 */}
                <div style={{ flex: 1, overflow: 'auto' }}>
                    <div style={{ padding: '16px 24px' }}>
                        <Space size="small" style={{ backgroundColor: '#fff', padding: '0 8px', marginBottom: 12 }}>
                            <CodeOutlined style={{ color: '#1890ff' }} />
                            <Text style={{ color: '#4e5969', fontSize: '13px' }}>
                                消息内容
                            </Text>
                        </Space>

                        {/* 带颜色的JSON内容展示区 */}
                        <div style={{
                            backgroundColor: '#fafafa',
                            borderRadius: '8px',
                            border: '1px solid #e8e8e8',
                            minHeight: '300px',
                            overflow: 'auto'
                        }}>
                            {messageDetail.content ? (
                                <pre style={{
                                    margin: 0,
                                    padding: 16,
                                    whiteSpace: 'pre-wrap',
                                    wordBreak: 'break-all',
                                    fontSize: '14px',
                                    lineHeight: 1.6,
                                    fontFamily: 'SFMono-Regular, Consolas, "Liberation Mono", Menlo, monospace'
                                }}>
                  {/* 渲染带颜色的JSON */}
                                    <code
                                        dangerouslySetInnerHTML={{
                                            __html: isJsonContent(messageDetail.content)
                                                ? formatJsonWithColor(messageDetail.content)
                                                : escapeHtml(messageDetail.content)
                                        }}
                                    />
                </pre>
                            ) : (
                                <div style={{
                                    height: '300px',
                                    display: 'flex',
                                    alignItems: 'center',
                                    justifyContent: 'center',
                                    color: '#86909c',
                                    fontSize: '14px'
                                }}>
                                    无消息内容
                                </div>
                            )}
                        </div>
                    </div>
                </div>
            </div>
        </Modal>
    );
};

export default MqDetail;